<script setup lang="ts">
import { ref } from 'vue';
import { labels } from '/@/api/admin/metaField';
import router from '/@/router';
import { saveFormJson, getFormJson } from '/@/api/admin/metaEntity';
import { ElMessage } from 'element-plus';
// 可以在此处获取设计器实例或进行其他操作
const designer = ref(null);
const entityId = router.currentRoute.value.query.entityId;
if (entityId == undefined) {
	window.location.reload();
}
const hasFieldName = [];
onMounted(() => {
	getFormJson(entityId).then((res) => {
		res.data.formJson.forEach((item) => {
			if (!(item.props instanceof Object)){
				item.props = {}
			}
		});
		designer.value.setRule(res.data.formJson);
		res.data.formJson.forEach((item) => {
			hasFieldName.push(item.field);
		});
	});
	const baseItemMap = {};
	designer.value.menuList[0].list.forEach((item) => {
		baseItemMap[item.name] = item;
	});
	designer.value.hiddenMenu.push('main', 'subform');
	designer.value.addMenu({
		name: 'test',
		title: '字段',
		list: [],
	});
	const menuItemList = [];
	labels(entityId).then((res) => {
		res.data.forEach((item) => {
			const flag = hasFieldName.indexOf(item.label) != -1;
			menuItemList.push({
				name: item.type,
				label: item.name,
				title: item.name,
				icon: baseItemMap[item.type].icon,
				field: item.label,
				mask: false,
				show: flag,
				props: {
					readonly: item.systemFieldFlag === 1,
				},
			});
		});
		designer.value.appendMenuItem('test', menuItemList);
	});

	const targetNode = document.querySelector('._fc-m-drag');

	const config = { childList: true, attributes: true, subtree: true };

	const callback = function () {
		const menuList = designer.value.menuList[4].list;
		menuItemList.map((item) => {
			return item.field;
		});

		menuList.forEach((item) => {
			item.show = designer.value.fields().indexOf(item.field) != -1;
		});
	};

	const observer = new MutationObserver(callback);

	if (targetNode) {
		observer.observe(targetNode, config);
	}
});
const config = {
	//控制字段ID只能选择,不能输入
	fieldReadonly: true,
};
const saveForm = () => {
	// console.log(designer.value);
	// console.log(designer.value.form);
	saveFormJson(entityId, JSON.parse(designer.value.getJson())).then((res) => {
		if (res.code == 0) {
			ElMessage({
				message: '保存成功',
				type: 'success',
			});
		} else {
			ElMessage.error('保存失败');
		}
	});
};
</script>

<template>
	<fc-designer ref="designer" :config="config" style="position: fixed; z-index: 4; left: 0; top: 0">
		<template #handle>
			<div class="handle">
				<el-button @click="saveForm" type="success" plain style="height: 25px; margin-right: 10px">保存</el-button>
			</div>
		</template>
	</fc-designer>
</template>

<style scoped lang="scss">
.el-form-item {
	margin-bottom: 10px !important;
}
</style>
